//简单的socket 服务器
package main

import (
	"fmt"
	//"io"
	"net"
	"os"
)

func main() {
	//定义端口号和地址还有接受数据的大小
	var (
		host   = "127.0.0.1"
		port   = "6666"
		remote = host + ":" + port
		data   = make([]byte, 1024)
	)

	//初始化链接服务器
	fmt.Println("Initiating server...(Ctrl+c to stop)")
	lis, err := net.Listen("tcp", remote)
	//defer lis.Close()  这句用了就内存出问题
	if err != nil {
		fmt.Println("Error when listen:", remote)
		os.Exit(1)
	}
	fmt.Println("starting the server")

	//循环监听链接
	for {
		var res string
		conn, err := lis.Accept()
		if err != nil {
			fmt.Println("Error accepting client: ", err.Error())
			os.Exit(0)
		}
		//连接后开启协程对话
		go func(con net.Conn) {
			defer con.Close()
			for {
				//读取内容
				length, err := con.Read(data)
				if err != nil {
					fmt.Printf("Client %s quit\n", con.RemoteAddr()) //这里如果是%v的话就会复制上一次的对话 然后再打印这行
					con.Close()
					return
				}

				//服务器说
				res = string(data[0:length])
				fmt.Printf("%s said: %s\n", con.RemoteAddr(), res)

				//客户端说
				res = "You said:" + res
				con.Write([]byte(res))

				//switch err {
				//case nil:
				//	res = string(data[0:length])
				//	fmt.Printf("%s said: %s\n", con.RemoteAddr(), res)
				//	res = "You said:" + res
				//	con.Write([]byte(res))
				//case io.EOF:
				//	fmt.Printf("Warning: End of data: %s \n", err)
				//	return
				//default:
				//	//fmt.Printf("Error: Reading data : %s \n", err)
				//	fmt.Printf("Client %s quit\n", con.RemoteAddr())
				//	//con.Close()
				//	return
				//}
			}
		}(conn)
	}

}
